<template>
  <section class="todoapp">
    
    <todu-header @add="handleAdd"></todu-header>
    <todu-main :list="list2" @del="handleDel" @state="handleState" @changeAllState="handleAllState"></todu-main>
    <todu-footer :flag="flag" :list="list" @clearCompleted="handleClear" @changeFlage="val => { flag = val }"></todu-footer>
    
  </section>
</template>

<script>

import ToduFooter from './components/ToduFooter.vue'
import ToduHeader from './components/ToduHeader.vue'
import ToduMain from './components/ToduMain.vue'

export default { 
  components: { ToduHeader,ToduMain, ToduFooter },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todu-list')) || [],
      // list: [
      //   { id: 12, name: '吃饭', isDone: false },
      //   { id: 14, name: '听歌', isDone: true },
      //   { id: 23, name: '洗澡', isDone: true },
      //   { id: 34, name: '睡觉', isDone: false },
      //   { id: 35, name: '游戏', isDone: false },
      // ],
      flag: 1    // 1-表示全部任务，2-表示进行中，3-表示已完成
    }
  },
  methods: {
    handleDel(id) {
      // console.log(id)
      this.list = this.list.filter(item => item.id !== id)
    },
    handleAdd (todu) {
      // console.log(todu)
      // this.list.push()     //  push 向数组的结尾添加元素
      this.list.unshift({
        id: Date.now(),
        name: todu,
        isDone: false
      }) 
    },
    handleState (id) {
      // console.log(id)
      // this.list.forEach(item => {
      //   if(item.id === id) {
      //     item.isDone = !item.isDone
      //   }
      // })
      const row = this.list.find(item => item.id === id)
      row.isDone = !row.isDone
    },
    handleClear () {
      //  isDone = true 的是已经完成，false是保留未完成的
      this.list = this.list.filter(item => item.isDone === false)
    },
    handleAllState (boo) {
      this.list.forEach(item => {
        item.isDone = boo     // 这里是一个等号， 赋值
      })
    }
  },
  computed: {
    list2 () {
      if(this.flag === 2) {
        return this.list.filter(item => item.isDone)
      } else if(this.flag === 3) {
        return this.list.filter(item => item.isDone === true)
      } else {
        return this.list
      }
    }
  },
  watch: {
    //  list () {},
    list: {
      handler (val) {
        localStorage.getItem('todu-list', JSON.stringify(val))
      },
      //  immediate: true,  // 立即侦听
      deep: true     //  深度侦听（用于侦听对象属性的变化）
    }
  }
}
</script>

<style></style>
